from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework import viewsets, status
from rest_framework.decorators import action

from ERP_system.utils.multiple_destory import MultipleDestoryMixin
from sys_manager.models import RolesModel,PermissionsModel
from ERP_system.apps.sys_manager.serializer_kit.roles_serializer import RolesSerializer,RolesPartialSerializer,RoleSetPermissionSerializer


class RolesView(ModelViewSet,MultipleDestoryMixin):

    queryset=RolesModel.objects.all()

    #重写序列化器类
    def get_serializer_class(self):
        if self.action == 'partial_update':
            return RolesPartialSerializer
        elif self.action == 'set_permission_to_role':
            return RoleSetPermissionSerializer
        else:
            return RolesSerializer
    #角色单一授权，一次只能授予一个角色单一权限，也可以取消一个权限
    @action(methods=['post'], detail=False)
    def set_permission_to_role(self,request,*args,**kwargs):
        ser=RoleSetPermissionSerializer(data=request.data)
        if ser.is_valid():
            #查询当前角色
            role=RolesModel.objects.get(id=ser.validated_data.get('role_id'))
            #查询当前权限
            permission=PermissionsModel.objects.get(id=ser.validated_data.get('permission_id'))
            if ser.validated_data.get('is_created'):

                role.permissions.add(permission)  #把当前的权限授予当前的角色
            else:
                role.permissions.remove(permission) #取消授权

            result=RolesSerializer(instance=role)
            return Response(data=result.data)

    def destroy(self, request, *args, **kwargs):
        if self.get_object().name=='admin':
            return Response(data={'detail':'admin角色不可删除'},status=status.HTTP_400_BAD_REQUEST)

    @action(methods=['delete'],detail=False)
    def multiple_destory(self,request,*args,**kwargs):
        delete_ids=request.data.get('ids')
        try:
            admin=RolesModel.objects.get(name='admin')
            if isinstance(delete_ids,list):
                if admin.id in delete_ids:
                    return Response(data={'detail':'admin角色不可删除'},status=status.HTTP_400_BAD_REQUEST)
        except RolesModel.DoesNotExist:
            pass


        RolesModel.objects.filter(id__in=delete_ids).delete()
        return Response(data={'message': '删除成功'}, status=status.HTTP_200_OK)

